package com.ithong.controller;

import cn.hutool.http.server.HttpServerRequest;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import io.netty.util.internal.StringUtil;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpRequest;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import java.util.UUID;

@RestController
@RequestMapping("/api")
public class KaptchController {

    @Autowired
    private DefaultKaptcha defaultKaptcha;
    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("/verification")
    public void createImageCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String uuid;
        Object o = redisTemplate.opsForValue().get("uuid");
        if (o == null) {
            uuid = UUID.randomUUID().toString().substring(0, 4);
            redisTemplate.opsForValue().set("uuid", uuid, 3600, TimeUnit.SECONDS);
            System.out.println("uuid:" + uuid);
        } else {
            uuid = (String) redisTemplate.opsForValue().get("uuid");
        }
        /*禁止缓存*/
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");
        // 生成文字验证码
        String text = defaultKaptcha.createText();
        // 生成图片验证码
        BufferedImage image = defaultKaptcha.createImage(text);
        // 设置过期时间

        redisTemplate.opsForValue().set(Constants.KAPTCHA_SESSION_KEY + uuid, text, 60, TimeUnit.SECONDS);
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
        out.flush();
        out.close();
    }
}